import os
import sys
import utils
from gtk import *
from xmmsclient import *
from os.path import basename
from urllib2 import url2pathname
from core import *




class Playlist(VBox, PlaylistCore):
    name = "Current playlist"
    position = 0
    CURRENT_POSITION = None

    def __init__(self, xmms2):
        VBox.__init__(self)
        PlaylistCore.__init__(self, xmms2)
        treeview = TreeView()
        utils.build_playlist(treeview)
        scroll = ScrolledWindow()
        scroll.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
        scroll.add(treeview)
        self.pack_start(scroll)
        treeview.connect("row-activated", self.on_row_activated)
        self.xmms2.broadcast_playlist_current_pos(self.mark_current_position)
        self.selection = treeview.get_selection()
    
    def select_all(self, *args):
        self.selection.select_all()
        
    def remove_selected(self, *args):
        model, path_list = self.selection.get_selected_rows()
        path_list.reverse()
        for p, in path_list:
            self.remove_entry(p)
    
    def on_row_activated(self, treeview, path, view_column):
        model = self.playlist.get_model()
        child_path = self.playlist.convert_path_to_child_path(path)
        position, = child_path
        self.xmms2.playlist_set_next(position)
        self.xmms2.playback_tickle()
        self.xmms2.playback_status(self.force_playing)

    def set_entry_col_title_from_res(self, res):
        if res.iserror():
            print "[Playlist]: could not set entry_col_title"
            return
        playlist_name = res.value()
        self.entry_col.set_title(playlist_name)

    def load_playlist(self, playlist=None):
        """Extends PlaylistCore method, setting the column name to 
        playlist"""
        if playlist is None:
            self.xmms2.playlist_current_active(
                cb=self.set_entry_col_title_from_res)
        else:
            self.entry_col.set_title(playlist)
        PlaylistCore.load_playlist(self, playlist)
    
    def unbold(self, position):
        """This will clear out the entry at position. That means it will
        no longer be marked as the 'current entry'"""
        model = self.playlist.get_model()
        iter = model.get_iter((position,))
        markup = model.get_value(iter, MARKUP)
        if markup.startswith("<b>") and markup.endswith("</b>"):
            new_markup = markup[3:-4]
        else:
            print "[unbold error]: malformed markup"
        model.set(iter, MARKUP, new_markup)
       
    def bold(self, position):
        """This will mark the current position. By default, it will bold 
        the current position entry"""
        model = self.playlist.get_model()
        iter = model.get_iter((position,))
        markup = model.get_value(iter, MARKUP)
        if markup.startswith("<b>") and markup.endswith("</b>"):
            print "[bold warning]: markup already bolded"
            return
        new_markup = "".join(["<b>", markup, "</b>"])
        model.set(iter, MARKUP, new_markup)
    
    def mark_current_position(self, res):
        if res.iserror():
            print "Could not set current position"
            return
        val = res.value()
        position = val["position"]
        playlist = val["name"]
        if self.CURRENT_POSITION is not None:
            self.unbold(self.CURRENT_POSITION)
        self.CURRENT_POSITION = position
        self.bold(position)

    def delete_selected(self):
    #def do_delete_your_rows(self):
        print "in"
        treeview = self.entry_col.get_tree_view()
        selection = treeview.get_selection()
        filter, treepath = selection.get_selected_rows()
        model = filter.get_model()
        treepath.reverse()
        for p in treepath:
            id = model.convert_path_to_child_path(p)
            self.xmms2.playlist_remove_entry(id, playlist=self.name)

if __name__ == "__main__":
    import xmmsclient.glib
    from xmmsclient import XMMS
    
    xmms2 = XMMS("xmms2test")
    try:
        xmms2.connect(os.getenv("XMMS_PATH"))
    except:
        print "Could not connect to xmms2d. Aborting"
        exit(1)
    xmmsclient.glib.GLibConnector(xmms2)
    
    pl = Playlist(xmms2)
    pl.set_name("my playlist")
    pl.load_playlist()
    w = Window()
    w.set_title("playlist widget")
    w.connect("delete-event", lambda w, e: main_quit())
    w.add(pl)
    w.show_all()
    #pl.xmms2.playlist_current_pos(cb=pl.mark_current_position)
    
    main()
